<template>
  <div class="login-container">
    <vue-particles
      color="#dedede"
      :particleOpacity="0.3"
      :particlesNumber="80"
      shapeType="circle"
      :particleSize="4"
      linesColor="#dedede"
      :linesWidth="1"
      :lineLinked="true"
      :lineOpacity="0.2"
      :linesDistance="150"
      :moveSpeed="3"empty
      :hoverEffect="true"
      hoverMode="grab"
      :clickEffect="true"
      clickMode="false"
      class="particles-js"
    ></vue-particles>
    <el-form autoComplete="on" :model="loginForm" :rules="loginRules" ref="loginForm" label-position="left"
             label-width="0px"
             class="card-box login-form">
      <h3 class="title">
        <img src="../../assets/login-head-1.png"/>
      </h3>
      <el-form-item prop="username">
        <el-input prefix-icon="fa fa-user" v-model="loginForm.username" autoComplete="on"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input prefix-icon="fa fa-lock" type="password" @keyup.enter.native="handleLogin"
                  v-model="loginForm.password"
                  autoComplete="on"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleLogin">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {getToken, setToken} from '@/utils/auth'
  import Tools from '@/utils/tools'
  import axios from 'axios'

  export default {
    name: 'login',
    components: {
      Tools
    },
    data() {
      return {
        webUrl: Tools.getWebURL(),
        loginForm: {
          username: '',
          password: ''
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', message: "请输入用户名"}],
          password: [{required: true, trigger: 'blur', message: "请输入密码"}]
        },
        loading: false
      }
    },
    methods: {
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            return new Promise((resolve, reject) => {
              axios.post(this.webUrl + '/cloud-auth/login/token',
                this.loginForm
              ).then((result) => {
                this.loading = false
                console.log(result)
                setToken(result.data.data.access_token);
                this.$router.push({path: '/'})
                resolve(result);
              }).catch(err => {
                this.loading = false
                reject(err)
              })
            })
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  @import "../../styles/mixin.scss";
  @import "../../views/login/index.scss";

  .particles-js {
    background-size: cover;
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    z-index: 0;
  }
</style>
